package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Set;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.value.Values;
import com.ruoyi.framework.web.service.SmsService;
import com.ruoyi.system.domain.WechatLoginBean;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api("登录验证")
@RestController
public class SysLoginController {
    @Autowired private SysLoginService loginService;

    @Autowired private ISysMenuService menuService;

    @Autowired private SysPermissionService permissionService;

    @Autowired private ISysDeptService deptService;

    @Autowired private SmsService smsService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 获取部门列表
     */
    @GetMapping("/login/dept/list")
    @ApiOperation("获取部门列表-无须登录")
    public AjaxResult deptList() {
        List<SysDept> depts = deptService.selectDeptList();
        return AjaxResult.success(depts);
    }

    /**
     * 根据code获取微信用的 openId,存入缓存
     */
    @GetMapping("/wx-open/{code}")
    @ApiOperation("根据code获取微信用的 openId")
    public AjaxResult wxOpen(@PathVariable("code")String code) throws Exception {
        return AjaxResult.success("获取成功").uuid(loginService.getWxOpenId(code));
    }

    /**
     * 微信小程序登录
     */
    @PostMapping("/login-wx")
    @ApiOperation("微信登录")
    @Log(title = "微信登录", businessType = BusinessType.OTHER)
    public AjaxResult wechatLogin(@Validated @RequestBody WechatLoginBean loginRequest) {
//        AjaxResult ajax = AjaxResult.success();
//        String token = loginService.wechatLogin(loginRequest);
//        return ajax.put(Constants.TOKEN, token);
        return loginService.wechatLogin(loginRequest);
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getDeptId());
        return ajax.put(Constants.TOKEN, token);
    }

    /**
     * 手机号登录方法
     *
     * @return 结果
     */
    @ApiOperation("手机号登录")
    @PostMapping("/login-sms")
    public AjaxResult smsLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.smsLogin(loginBody.getMobile(), loginBody.getSmsCode(), loginBody.getUuid());
        return ajax.put(Constants.TOKEN, token);
    }


    /**
     * 发送短信验证码-登录使用
     */
    @GetMapping("/sendSmsCode-login/{phone}")
    @ApiOperation("发送短信验证码-登录使用")
    @RateLimiter(key = Values.PHONE_CODE_LIMIT, count = 2, limitType = LimitType.IP)
    public AjaxResult sendSmsLoginCode(@PathVariable("phone") String phone) {
        String uuid = smsService.sendSmsCode(phone, false);
        return AjaxResult.success("发送成功").put("uuid", uuid);
    }

    /**
     * 发送短信验证码-注册使用
     */
    @GetMapping("/sendSmsCode-register/{phone}")
    @ApiOperation("发送短信验证码-注册使用")
    @RateLimiter(key = Values.PHONE_CODE_LIMIT, count = 2, limitType = LimitType.IP)
    public AjaxResult sendSmsRegisterCode(@PathVariable("phone") String phone) {
        if (!"true".equals(configService.selectConfigByKey("sys.account.registerUser"))) {
            return AjaxResult.error("当前系统没有开启注册功能！");
        }
        String uuid = smsService.sendSmsCode(phone, true);
        return AjaxResult.success("发送成功").put("uuid", uuid);
    }

    /**
     * 获取用户信息
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("获取用户信息")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @ApiOperation("获取路由信息")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
